package com.systar.activity.report.users;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;

public class UserProvider
{
	Map<String,User> usersAndRoles;
	
	public UserProvider()
	{
		usersAndRoles = new HashMap<String,User>();
	}
	
	/**
	 * Load role definitions
	 * For this simple example, users are stored the same way as Jetty
	 * <code>user=password[,role1[,role2]]</code>
	 * @throws IOException if could not load users
	 */
	public void load() throws IOException
	{
		Properties usersStore = new Properties();
		usersStore.load(UserProvider.class.getResourceAsStream("users.properties"));
		for (String userName : usersStore.stringPropertyNames())
		{
			String passAndRoles = usersStore.getProperty(userName, "");
			StringTokenizer tok = new StringTokenizer(passAndRoles, ",");
			
			// password
			String password = (tok.hasMoreTokens()) ? tok.nextToken() : "";

			// roles
			ArrayList<Role> list = new ArrayList<Role>();
			while (tok.hasMoreTokens())
			{
				Role role = Role.fromString(tok.nextToken());
				if (role != null)
					list.add(role);
			}
			
			User user = new User(userName, list.toArray(new Role[list.size()]));
			usersAndRoles.put(userName+":"+password, user);
		}
	}

	/**
	 * Search User from its specification 
	 * 
	 * @param userSpecification specification in "user:password" format
	 * @return a new User instance, or null if not found
	 */
	public User searchUser(String userSpecification)
	{
		return usersAndRoles.get(userSpecification);
	}
	
}
